using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthBar:MonoBehaviour {
	void Start() {
		GetComponentReference();
	}
	void Update() {
		UpdateValue();
		UpdateImage();
	}

	//unity reference
	public Mob mob;
	Image overlayRed;
	Image overlayWhite;

	[SerializeField]
	float whiteRetractDelay = 0.1f;
	[SerializeField]
	float whiteRetractSpeed = 3;

	float ratioWhite = 1;
	float ratioRed = 1;

	void GetComponentReference() {
		mob=GetComponentInParent<Mob>();
		Image[] images = GetComponentsInChildren<Image>();
		foreach(Image i in images) {
			if(i.name=="HealthBarOverlayWhite") overlayWhite=i;
			if(i.name=="HealthBarOverlayRed") overlayRed=i;
		}
	}

	void UpdateValue() {
		if(!mob) return;
		ratioRed=mob.HP/mob._maxHP;
		if(ratioWhite>ratioRed&&mob.timeAfterHit>whiteRetractDelay) ratioWhite=Mathf.Max(ratioRed,ratioWhite-whiteRetractSpeed*Time.deltaTime*mob.localTimeScale);
	}
	void UpdateImage() {
		overlayRed.fillAmount=ratioRed;
		overlayWhite.fillAmount=ratioWhite;
	}
}